package cn.wolfcode.wms.web.controller;

import cn.wolfcode.wms.domain.SystemMenu;
import cn.wolfcode.wms.qo.SystemMenuQueryObject;
import cn.wolfcode.wms.service.ISystemMenuService;
import cn.wolfcode.wms.util.JSONResult;
import cn.wolfcode.wms.util.PageResult;
import cn.wolfcode.wms.util.RequiredPermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Optional;

@Controller
@RequestMapping("systemMenu")
public class SystemMenuController {
    @Autowired
    private ISystemMenuService systemMenuService;
    @RequestMapping("list")
    public String list(@ModelAttribute("qo") SystemMenuQueryObject qo, Model model){
        //如果不是顶级菜单,要查出面包屑
        if (Optional.ofNullable(qo.getParentId()).isPresent()) {
            List<SystemMenu> parentMenus = systemMenuService.getParentMenus(qo.getParentId());
            //将父菜单共享到页面中
            model.addAttribute("parentMenus",parentMenus);
        }
        PageResult result = systemMenuService.query(qo);
        model.addAttribute("result",result);
        return "systemMenu/list";
    }
    @RequestMapping("input")
    public String input(Long id, Long parentId, Model model){
        if (Optional.ofNullable(parentId).isPresent()) {
            //查询当前父菜单并共享
            model.addAttribute("parent",systemMenuService.get(parentId));
        }
        if (Optional.ofNullable(id).isPresent()) {
            //查询当前菜单
            model.addAttribute("entity",systemMenuService.get(id));
        }
        return "systemMenu/input";
    }

    @RequiredPermission("删除菜单")
    @RequestMapping("delete")
    @ResponseBody
    public Object delete(Long id){
        if (Optional.ofNullable(id).isPresent()) {
            systemMenuService.delete(id);
        }
        return new JSONResult();
    }

    @RequestMapping("saveOrUpdate")
    public String saveOrUpdate(SystemMenu entity){
        systemMenuService.saveOrUpdate(entity);
        return "redirect:/systemMenu/list.do";
    }

    @RequestMapping("getMenusBySn")
    @ResponseBody
    public Object getMenusBySn(String menuSn){
        return systemMenuService.getMenusBySn(menuSn);
    }
}
